/**
 * @Author: colpu
 * @Date: 2025-03-29 19:38:16
 * @LastEditors: colpu ycg520520@qq.com
 * @LastEditTime: 2025-10-17 15:37:02
 * @
 * @Copyright (c) 2025 by colpu, All Rights Reserved.
 */
import debugFactory from "debug";
import Application from "koa"; // 引入Koa框架库
import Context from "./context.js";
import timing from "./utils/timing.js";
import { loadFile, getLocalIP } from "./utils/index.js";
import { CORE_LOADER } from "./constants.js"; // 引入全局loader标识
const debug = debugFactory("core:index");
const PROCESS_CWD = process.cwd(); // 进程启动位置
const resolve = import.meta.resolve;

export { Context as Controller, Context as Service, timing };

/**
 * @class Server
 * @param {object} [options] Application options
 * @param {string} [options.env='development'] Environment
 * @param {string[]} [options.keys] Signed cookie keys
 * @param {boolean} [options.proxy] Trust proxy headers
 * @param {number} [options.subdomainOffset] Subdomain offset
 * @param {boolean} [options.proxyIpHeader] proxy ip header, default to X-Forwarded-For
 * @param {boolean} [options.maxIpsCount] max ips read from proxy ip header, default to 0 (means infinity)
 */
export default class Server extends Application {
  constructor(options = {}) {
    super(options);
    this.options = options;
    this.root = PROCESS_CWD;

    // 挂载基础类
    this.Controller = Context;
    this.Service = Context;
  }

  /**
   * @function start 服务启动方法
   * @param {Function} callback 程序启动端口
   */
  async start(callback) {
    await this._initLoader();

    const _this = this;
    _this.listen(_this.port, (err) => {
      if (err) {
        throw err;
      }
      getLocalIP((msg, ips) => {
        if (ips === null) {
          console.log("无法获取本地IP地址，请检查网络连接");
          return;
        }
        let ipMsg = "应用启动在:\n";
        ips.forEach((ip, index) => {
          if (index > 1) return; // 最多显示2个ip
          ipMsg += `http://${ip}:${_this.port}\n`;
        });
        console.info(ipMsg);
      });

      if (typeof callback === "function") {
        callback(_this);
      }
    });
    return _this;
  }

  async _initLoader() {
    const Loader = await this[CORE_LOADER];
    debug("require loader %o", Loader);
    this.loader = new Loader(this);
    await this.loader.init();
  }

  /**
   * @getter CORE_LOADER
   * @return {Object} 返回loader
   */
  get [CORE_LOADER]() {
    return loadFile(resolve("./loader/index.js"));
  }

  /**
   * @getter name
   * @return {String} 返回应用名称
   */
  get name() {
    return this.loader ? this.loader.pkg.name : "";
  }

  /**
   * @getter pkg
   * @return {String} 返回应用名称
   */
  get pkg() {
    return this.loader ? this.loader.pkg : {};
  }

  /**
   * @getter config
   * @return {Object} 返回应用配置
   */
  get config() {
    return this.loader ? this.loader.config : {};
  }

  get port() {
    return this.config.port;
  }
}
